﻿Imports ISNet.WebUI.WebGrid
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Collections.Generic
Imports System.Linq
Imports ISNet.WebUI.WebTreeView
Imports System.IO
Imports Microsoft.VisualBasic.FileIO.TextFieldParser
Imports log4net

Partial Class mtUsers
    Inherits System.Web.UI.Page

    Public AlertText As String

    Private Shared logger As ILog = LogManager.GetLogger("mtUsers")

    Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        WebCombo3.EncodeOutput = True
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Session("PlanYear") = "2557"
        ScreenName.Text = "ระบบจัดทำงบประมาณ  >>  ตั้งค่าระบบ >> ผู้ใช้งาน"
        'Session("users") = "bb0011"
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If

        If IsPostBack = False Then

            Session.Remove("Search")
            Session.Remove("search_fctr")
            ' PlanYearsTxt.Text = Session("PlanYear")
            Session("PlanYearTxt") = Session("PlanYear")
            'Session("SearchTxt") += " and PlanYear = " & PlanYearsTxt.Text

        End If
        'GenerateValues()
        Dim adapter As New MasterDataSetTableAdapters.FundCentersTableAdapter
        Dim data As New MasterDataSet.FundCentersDataTable
        ' data = adapter.GetDataByPlanYear()
        data = adapter.GetDataByPlanYear(Val(Session("PlanYearTxt")))

        ms8.DataValueField = "FundCenterCode"
        ms8.DataTextField = "Description"
        ms8.DataSource = data
        ms8.DataBind()
        Session("SearchTxt") = ""
    End Sub

    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource

        Dim adapter As New MasterDataSetTableAdapters.UsersTableAdapter
        Dim dtTable As New MasterDataSet.UsersDataTable

        Dim sql As String = "select a.*,(SELECT COUNT(*) AS Expr1 FROM LoginLog WHERE (UserName = a.UserName)) as isLogin from users a "
        sql += " WHERE 1 = 1 "
        ' sql += " and PlanYear like '" & PlanYearsTxt.Text & "'"
        sql += Session("SearchTxt")

        sql += " ORDER BY FirstName, LastName "

        adapter.SearchUsers(dtTable, sql)
        'Response.Write(sql)

        Session("count_data") = dtTable.Rows.Count

        dtTable.Columns("username").AllowDBNull = True
        dtTable.Columns("FundCenter_FundCenterCode").AllowDBNull = True
        dtTable.Columns("FundCenter_PlanYear").AllowDBNull = True
        dtTable.Columns("Enable_All_Report_Flag").AllowDBNull = True
        e.DataSource = dtTable

    End Sub

    Protected Sub WebGrid1_InitializeRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        ' don't edit column
        e.Row.Cells(8).ForceNoEdit = True
        e.Row.Cells(9).ForceNoEdit = True

        Dim container As ISNet.WebUI.WebGrid.WebGridCellTemplateContainer
        container = e.Row.Cells(8).GetTemplateContainer()
        Dim myImage As Image
        myImage = container.FindControl("Image1")
        'Dim UserName As String
        'UserName = e.Row.Cells.GetNamedItem("UserName").Value
        'Dim adapter As New LoginDSTableAdapters.LoginLogTableAdapter
        'Dim exist As Integer
        'exist = adapter.CheckExistUser(UserName)

        Dim exist As Integer = e.Row.Cells(8).Value
        If exist > 0 Then
            myImage.Visible = True
        Else
            myImage.Visible = False
        End If

    End Sub

    Protected Sub WebGrid1_AddRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        Dim adapter As New MasterDataSetTableAdapters.UsersTableAdapter

        Dim check = adapter.CheckExistFirst_LastnameUsers(Trim(e.Row.Cells(2).Value), Trim(e.Row.Cells(3).Value))
        Dim check2 = adapter.CheckExistEmail(Trim(e.Row.Cells(4).Value))
        Dim check3 = adapter.CheckExistUsersName(Trim(e.Row.Cells(1).Value))

        Dim alert As String = "ข้อมูล"
        Dim i As Integer = 0
        'If Val(check) <> 0 Then
        '    WebGrid1.ClientAction.Refresh()
        '    alert += "ชื่อและนามสกุล"
        '    i += 1
        'ElseIf Val(check2) <> 0 Then
        '    alert += "อีเมล์"
        '    i += 1
        'ElseIf Val(check3) <> 0 Then
        '    alert += "ชื่อผู้ใช้งาน"
        '    i += 1
        'End If
        If Val(check3) <> 0 Then
            alert += "ชื่อผู้ใช้งาน"
            i += 1
        End If
        If i <> 0 Then
            WebGrid1.ClearCachedDataSource()
            WebGrid1.ClientAction.Refresh()
            Throw New ArgumentException(alert + "ซ้ำกับที่มีอยู่ กรุณาตรวจสอบ")

        Else
            Dim id As Decimal
            id = adapter.InsertUsers(Trim(e.Row.Cells(1).Value), Trim(e.Row.Cells(2).Value), Trim(e.Row.Cells(3).Value), Trim(e.Row.Cells(4).Value), Trim(e.Row.Cells(6).Value), Date.Now, Session("users"), e.Row.Cells(5).Value, Session("PlanYearTxt"), e.Row.Cells(7).Value)
            Dim dr As DataRow = e.Row.DataRow
            dr("id") = id

            logger.Info("User " & Session("users") & " insert user name " & e.Row.Cells(1).Value)
            'WebGrid1.ClientAction.Refresh()
        End If

    End Sub
    Protected Sub WebGrid1_UpdateRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        Dim id As String
        id = e.Row.KeyValue
        'WebGrid1.ClientAction.Alert(iyear)

        Dim adapter As New MasterDataSetTableAdapters.UsersTableAdapter
        Dim check = adapter.CheckExistFirst_LastnameUsers(Trim(e.Row.Cells(2).Value), Val(e.Row.Cells(3).Value))
        Dim check2 = adapter.CheckExistEmail(Trim(e.Row.Cells(4).Value))
        Dim check3 = adapter.CheckExistUpdate(Trim(e.Row.Cells(1).Value), id)

        Dim alert As String = "ข้อมูล"
        Dim i As Integer = 0
        'If Val(check) > 1 Then
        '    WebGrid1.ClientAction.Refresh()
        '    alert += "ชื่อและนามสกุล"
        '    i += 1
        'ElseIf Val(check2) > 1 Then
        '    alert += "อีเมล์"
        '    i += 1
        'ElseIf Val(check3) > 1 Then
        '    alert += "ชื่อผู้ใช้งาน"
        '    i += 1
        'End If
        If Val(check3) <> 0 Then
            alert += "ชื่อผู้ใช้งาน"
            i += 1
        End If
        If i <> 0 Then
            WebGrid1.ClearCachedDataSource()
            Throw New ArgumentException(alert + "ซ้ำกับที่มีอยู่ กรุณาตรวจสอบ")
            'WebGrid1.ClientAction.Refresh()
        Else
            adapter.UpdateUsers(Trim(e.Row.Cells(1).Value), Trim(e.Row.Cells(2).Value), Trim(e.Row.Cells(3).Value), Trim(e.Row.Cells(4).Value), Trim(e.Row.Cells(6).Value), Date.Now, Session("users"), e.Row.Cells(5).Value, Session("PlanYearTxt"), e.Row.Cells(7).Value, id)
            logger.Info("User " & Session("users") & " update user name " & e.Row.Cells(1).Value)
        End If
    End Sub

    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim type_del As String = TryCast(Request("type_del"), String)
            Dim Deletet As String = TryCast(Request("id"), String)

            Dim Datalist() As String
            Datalist = Split(Deletet, ",")

            Dim opt As Integer
            opt = Val(Datalist(1))
            Dim adapter As New MasterDataSetTableAdapters.UsersTableAdapter
            Dim adapteruf As New MasterDataSetTableAdapters.UserFundCentersTableAdapter
            Dim l_adapter As New LoginDSTableAdapters.LoginLogTableAdapter
            If type_del = "1" Then
                If opt = 1 Then
                    Dim UserName As String
                    UserName = l_adapter.GetUserNameByID(Val(Datalist(0)))
                    adapteruf.DeleteByUserName(UserName)
                    adapter.DeleteUsers(Val(Datalist(0)))
                    logger.Info("User " & Session("users") & " delete user name " & Datalist(0))

                Else

                    Dim UserName As String
                    Try
                        UserName = l_adapter.GetUserNameByID(Val(Datalist(0)))
                    Catch ex As Exception
                        UserName = "xxx"
                    End Try

                    l_adapter.DeleteByUser(UserName)
                    logger.Info("User " & Session("users") & " delete user name " & UserName)
                End If
            ElseIf type_del = "2" Then
                'MsgBox(opt)
                If opt = 1 Then


                    For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                        'MsgBox(Val(keyValue))
                        Dim UserName As String
                        UserName = l_adapter.GetUserNameByID(keyValue)
                        adapteruf.DeleteByUserName(UserName)
                        adapter.DeleteUsers(keyValue)
                        logger.Info("User " & Session("users") & " delete user name " & keyValue)
                    Next keyValue

                Else
                    Dim UserName As String
                    Try
                        UserName = l_adapter.GetUserNameByID(Val(Datalist(0)))
                    Catch ex As Exception
                        UserName = "xxx"
                    End Try

                    For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                        l_adapter.DeleteByUser(keyValue)
                        logger.Info("User " & Session("users") & " delete user name " & keyValue)
                    Next keyValue

                End If
            End If
            WebGrid1.ClientAction.Refresh()
        End If
    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        Session("SearchTxt") = ""
        'Session("PlanYearTxt") = PlanYearsTxt.Text
        '  Session("SearchTxt") = " AND FundCenter_PlanYear = " & Val(Session("PlanYearTxt"))

        If (UserNameTxt.Text <> " " And UserNameTxt.Text <> "") Then
            Session("SearchTxt") += " and username like '%" & UserNameTxt.Text & "%'"
        End If
        If (FnameTxt.Text <> " " And FnameTxt.Text <> "") Then
            Session("SearchTxt") += " and FirstName like '%" & FnameTxt.Text & "%'"
        End If
        If (LnameTxt.Text <> " " And LnameTxt.Text <> "") Then
            Session("SearchTxt") += " and LastName like '%" & LnameTxt.Text & "%'"
        End If


        If TabContainer1.ActiveTab.ID = TabPanel1.ID Then

            If hdf1.Value.ToString <> "" Then
                Session("SearchTxt") += " AND FundCenter_FundCenterCode IN ("
                Dim Numx As Array = hdf1.Value.Split(",")
                For i = 0 To Numx.Length - 1
                    If Val(Numx(i)) <> 0 Then
                        If i <> 0 Then
                            Session("SearchTxt") += ",'"
                        Else
                            Session("SearchTxt") += "'"
                        End If
                        Session("SearchTxt") += Numx(i).ToString & "'"
                    Else
                        Session("SearchTxt") += "''"
                    End If

                Next
                Session("SearchTxt") += ") "
            End If
            '      GenerateValues()
        Else
            Session("SearchTxt") += " AND FundCenter_FundCenterCode IN ("
            Session("SearchTxt") += GetSubFCTR(WebCombo3.Value, Val(Session("PlanYearTxt")))
            Session("SearchTxt") += ") "
        End If



        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
        t_countdata.Visible = True
        If Val(Session("count_data")) > 0 Then
            L_CountData.Text = FormatNumber(Val(Session("count_data")), 0) & " รายการ"
        Else
            L_CountData.Text = "ไม่พบข้อมูลที่ค้นหา"
        End If
        fctrObjectDataSource.DataBind()
        'GenerateValues()

        'Dim adapter As New MasterDataSetTableAdapters.FundCentersTableAdapter
        'Dim data As New MasterDataSet.FundCentersDataTable
        'data = adapter.GetDataByPlanYear(Session("PlanYearTxt"))

        'ms8.DataValueField = "FundCenterCode"
        'ms8.DataTextField = "Description"
        'ms8.DataSource = data
        'ms8.DataBind()
    End Sub

    Sub GenerateValues()
        If hdf1.Value.Length = 0 Then
            Session("Search") = "false"
        End If
        Try
            Dim Numx As Array = hdf1.Value.Split(",")

            For i = 0 To Numx.Length - 1
                ms8.Items.FindByValue(Numx(i).ToString).Selected = True
                'Response.Write(Numx(i).ToString)
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

    End Sub

    'Protected Sub FundCenterCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles FundCenterCombo.InitializeDataSource
    '    Dim ds As New DataSet


    '    Dim adapter As New MasterDataSetTableAdapters.FundCentersTableAdapter
    '    Dim datatable As New MasterDataSet.FundCentersDataTable
    '    datatable = adapter.GetDataByPlanYear(Val(Session("PlanYearTxt")))
    '    e.DataSource = datatable



    'End Sub

    Protected Sub SaveBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SaveBtn.Click
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
    End Sub

    Sub Alert(ByVal message As String)
        AlertText += "<script> alert('" & message & "');</script>"
    End Sub

    Protected Sub UploadBtn_Click(sender As Object, e As ImageClickEventArgs) Handles UploadBtn.Click
        Dim Extension As String = ""
        'Dim FileName As String = ""
        Dim Filedata As String
        If FileUpload1.HasFile Then
            Try
                'FileUpload1.SaveAs(Server.MapPath("~/Temp/") & FileUpload1.FileName)
                Extension = System.IO.Path.GetExtension(FileUpload1.FileName)
                'FileUpload1.SaveAs(Server.MapPath("~/Temp/") & FileName)

                Dim b As New BinaryReader(FileUpload1.FileContent)
                Dim binData As Byte() = b.ReadBytes(FileUpload1.FileContent.Length)
                b.Dispose()
                Filedata = System.Text.Encoding.Default.GetString(binData)

            Catch ex As Exception
                Alert("มีข้อผิดพลาดในการ Upload ไฟล์")
                Exit Sub
            End Try
        Else
            Alert("กรุณาระบุไฟล์")
            Exit Sub
        End If


        Dim delimeter As String = ","
        Dim DataArray() As String

        Dim streader As New StringReader(Filedata)
        Dim line As String = "a"
        Dim linecount As Integer = 0
        Dim success As Integer = 0
        Dim adapter As New MasterDataSetTableAdapters.UsersTableAdapter
        Dim err As Integer = 0
        Dim err2 As Integer = 0
        While (line <> Nothing)
            line = streader.ReadLine()
            linecount += 1
            If linecount = 1 Then
                Continue While
            End If
            DataArray = Split(line, delimeter)

            If line Is Nothing Then
                Continue While
            End If
            If DataArray.Count < 7 Then
                err2 += 1
                Continue While
            End If
            If Len(line.Trim) > 0 Then

                Dim username As String = ""
                Dim firstnane As String = ""
                Dim lastname As String = ""
                Dim email As String = ""
                Dim fctr As String = ""
                Dim role As String = ""
                Dim year As String = ""
                Dim enableAllReport As Boolean = False

                Try
                    username = DataArray(0)
                    firstnane = DataArray(1)
                    lastname = DataArray(2)
                    email = DataArray(3)
                    fctr = DataArray(4)
                    role = DataArray(5)
                    year = DataArray(6)
                    enableAllReport = Convert.ToBoolean(DataArray(7))

                    Dim check3 = adapter.CheckExistUsersName(username.Trim)
                    If Val(check3) = 0 Then
                        adapter.InsertUsers(username.Trim, firstnane, lastname, email, role, Date.Now, Session("users"), fctr, year, enableAllReport)
                    Else
                        adapter.UpdateByUserName(firstnane, lastname, email, role, Date.Now, Session("users"), fctr, year, username.Trim, enableAllReport)
                    End If
                    success += 1
                Catch ex As Exception
                    err += 1
                    'MsgBox(ex.Message)
                    Continue While
                End Try
            End If
        End While
        If err > 0 Then
            Alert("ไม่พบ Fund Center ในระบบของปีงบประมาณในรายการที่อัพโหลด")
        End If
        If err2 > 0 Then
            Alert("Format ไม่ถูกต้องจำนวน " & err2 & " รายการ กรุณาตรวจสอบ")
        End If
        If success > 0 Then
            logger.Info("User " & Session("users") & " upload users with total amount " & linecount.ToString)
            Alert("ทำการเพิ่มข้อมูลผู้ใช้งานเรียบร้อยแล้ว\nเพิ่มข้อมูลสำเร็จทั้งหมด " & success & " รายการ")
        End If
    End Sub

    Protected Sub WebCombo3_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo3.InitializeDataSource

        Dim adap As New FundCenterParentTableAdapters.SelectorTableAdapter
        Dim dt As New FundCenterParent.SelectorDataTable
        Dim dt2 As New FundCenterParent.SelectorDataTable
        Dim sql = ""
        Dim prefil As String = ""
        'prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FctH.PlanYear = " & Val(Session("PlanYear"))
        'If prefil <> "" Then
        '    sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        'End If
        sql += "ORDER BY Grouppath"
        adap.GetDataByFilter(dt2, sql)
        dt.Rows.Add("ทุกรายการ", "0", 0, "0", Val(Session("PlanYear")), "ทุกรายการ")
        dt.Merge(dt2)
        'dt.DefaultView.Sort = "FundCenter_FundCenterCode"
        e.DataSource = dt



    End Sub

    Function GetSubFCTR(ByVal fctr_code As String, ByVal planyear As Integer) As String

        Dim gpath As String
        If fctr_code = "0" Then
            gpath = ""
        Else
            Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
            Dim Hdatatable As New FundCenterParent.FctHDataTable
            Hdatatable = Hadapter.GetDataByFctr(fctr_code, planyear)
            For Each row As FundCenterParent.FctHRow In Hdatatable
                gpath = row.grouppath
            Next
        End If
        Dim Hadapter2 As New FundCenterParentTableAdapters.FctH2TableAdapter
        Dim Hdatatable2 As New FundCenterParent.FctH2DataTable
        Dim sql As String = ""
        sql += "SELECT  Fcth.FundCenter_FundCenterCode FROM FctH , fctr_view  "
        sql += "WHERE Fcth.Fundcenter_FundcenterCode = fctr_view.Fundcentercode AND Grouppath like '" & gpath & "%'"
        sql += " AND Fcth.PlanYear = " & planyear & " And Fctr_view.PlanYear = " & planyear

        Return sql
    End Function

End Class
